<?php

namespace App\Task\v1_1_0;

use App\Model\CallBase;
use App\Model\ChangeHostLog;
use App\Model\Message;
use App\Model\VideoCall;
use App\Model\VoiceCall;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * 随心聊 - 正在呼叫的记录（切换主播）
 * @Crontab(name="CheckQuickCallTask", rule="*\/10 * * * * *", callback="execute", memo="检测随心聊通话",singleton=false)
 */
class CheckQuickCallTask
{
    //超过秒数会切换主播
    protected $lmtDuration = 10;
    protected $maxWaiting = 180;

    public function execute()
    {
        $this->runCheck(VideoCall::class);
        $this->runCheck(VoiceCall::class);
    }

    function runCheck($callCls = null)
    {
        //获取当前一键语聊正在拨叫的用户
        $callingLogs = $callCls::getQuickCalling();
        if (empty($callingLogs)) return;
        log_info(__CLASS__ . "=={$callCls}==docheck==" . date('Y-m-d H:i:s') . "==Count:" . count($callingLogs));

        //轮询
        foreach ($callingLogs as $k => $log) {
            $duration = time() - $log['start_time'];
            //没有超时不处理
            if ($duration < $this->lmtDuration) {
                log_info(__CLASS__ . "=={$callCls}==passcheck==Continue::LogId::{$log['id']}");
                continue;
            } elseif ($duration >= $this->lmtDuration && $duration < $this->maxWaiting) {
                log_info(__CLASS__ . "=={$callCls}==changehost==Change::LogId::{$log['id']}");
                //透传消息-切换主播
                Message::sendSlient($log['user_id'], 'CHANGE_FOR_QUICK');
                //主叫挂断
                $callCls::where('id', $log['id'])->limit(1)->update(['status' => CallBase::STATUS_CALLER_STOP]);
            } else {
                //无效状态
                $callCls::where('id', $log['id'])->limit(1)->update(['status' => CallBase::STATUS_INVALID]);
                //透传消息-切换主播
                // Message::sendSlient($log['user_id'], 'HANGUP_CALL');
                log_info(__CLASS__ . "=={$callCls}==hangup==Change::LogId::{$log['id']}");
            }
        }
    }
}
